﻿using System;
using System.Data;
using System.Data.SQLite;
using System.IO;

namespace Project
{
    public static class DatabaseHelper
    {
        private static string dbFile = "ImageViewer.db";
        private static string connectionString = $"Data Source={dbFile};Version=3;";

        public static void InitializeDatabase()
        {
            if (!File.Exists(dbFile))
                SQLiteConnection.CreateFile(dbFile);

            using (var conn = new SQLiteConnection(connectionString))
            {
                conn.Open();
                string createTable = @"CREATE TABLE IF NOT EXISTS ImageHistory (
                    Id INTEGER PRIMARY KEY AUTOINCREMENT,
                    FilePath TEXT NOT NULL,
                    LoadedAt DATETIME NOT NULL
                );";

                using (var cmd = new SQLiteCommand(createTable, conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }

        public static void InsertImageRecord(string filePath)
        {
            using (var conn = new SQLiteConnection(connectionString))
            {
                conn.Open();
                string insert = "INSERT INTO ImageHistory (FilePath, LoadedAt) VALUES (@path, @time)";
                using (var cmd = new SQLiteCommand(insert, conn))
                {
                    cmd.Parameters.AddWithValue("@path", filePath);
                    cmd.Parameters.AddWithValue("@time", DateTime.Now);
                    cmd.ExecuteNonQuery();
                }
            }
        }

        public static DataTable GetImageHistory()
        {
            using (var conn = new SQLiteConnection(connectionString))
            {
                conn.Open();
                string query = "SELECT * FROM ImageHistory ORDER BY LoadedAt DESC";
                using (var adapter = new SQLiteDataAdapter(query, conn))
                {
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

